package com.star.percalservice.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.star.percalservice.mapper.ResearchProjectMapper;
import com.star.percalservice.mapper.TeacherMapper;
import com.star.percalservice.mapper.UserMapper;
import com.star.percalservice.model.dto.ResearchProjectDTO;
import com.star.percalservice.model.entity.ResearchProject;
import com.star.percalservice.model.entity.Teacher;
import com.star.percalservice.model.entity.User;
import com.star.percalservice.model.vo.ProjectVO;
import com.star.percalservice.service.ResearchProjectService;
import com.star.percalservice.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author star
 * @version 1.0
 * @Description:
 * @DateTime 2025/4/13 3:48
 */
@Service
public class ResearchProjectServiceImpl implements ResearchProjectService {

    @Autowired
    private ResearchProjectMapper researchProjectMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public R list(ResearchProjectDTO researchProjectDTO) {
        List<ResearchProject> list = researchProjectMapper.list(researchProjectDTO);
        List<ProjectVO> resList = new ArrayList<>();
        list.forEach(researchProject -> {
            ProjectVO projectVO = new ProjectVO();
            projectVO.setProject(researchProject);
            Teacher teacher = teacherMapper.selectById(researchProject.getTeacherId());
            User user = userMapper.selectById(teacher.getUserId());
            projectVO.setTeacherName(user.getRealName());
            projectVO.setDepartmentName(teacher.getDepartment());
            resList.add(projectVO);
        });
        return R.ok("查询成功", resList);
    }

    @Override
    public R add(ResearchProject researchProject) {
        QueryWrapper<ResearchProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", researchProject.getName());
        if (ObjectUtil.isNotNull(researchProjectMapper.selectOne(queryWrapper))) {
            return R.error("项目名称已存在");
        }
        return researchProjectMapper.insert(researchProject) > 0 ? R.ok("添加成功") : R.error("添加失败");
    }

    @Override
    public R update(ResearchProject researchProject) {
        return researchProjectMapper.updateById(researchProject) > 0 ? R.ok("修改成功") : R.error("修改失败");
    }

    @Override
    public R delete(Integer id) {
        return researchProjectMapper.deleteById(id) > 0 ? R.ok("删除成功") : R.error("删除失败");
    }
}
